package visualization
{
	import model.Field;
	import model.Model;
	
	import mx.controls.Label;
	import mx.core.UIComponent;
	import mx.effects.Move;
	import mx.effects.Resize;
	import mx.events.PropertyChangeEvent;
	import mx.events.PropertyChangeEventKind;
	import mx.utils.ObjectProxy;
	
	public class DataPoint extends UIComponent implements IDataPoint
	{
		/*====================
		 * Variables
		 *====================
		 */
		
		// IDataPoint variables
		[Bindable] public var title:String = "Data Point";
		[Bindable] public var model:Model;
		[Bindable] public var fields:Array = new Array();
		[Bindable] public var moveTween:Move;
		[Bindable] public var resizeTween:Resize;
		
		private var _source:Object;
		public function get source():Object{
			return this._source;
		}
		public function set source( obj:Object ):void{
			if(this._source is ObjectProxy){
				(this._source as ObjectProxy).removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, this.handlePropertyChange);
			}
			this._source = obj;
			if(this._source is ObjectProxy){
				(this._source as ObjectProxy).addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, this.handlePropertyChange);
			}
		}
		
		/*====================
		 * Constructor
		 *====================
		 */
		public function DataPoint()
		{
			this.moveTween = new Move(this);
			this.resizeTween = new Resize(this);
		}
		
		/*====================
		 * Methods
		 *====================
		 */
		public function getData( field:Field ):Object{
			return this._source[field.fieldName];
		}
		
		public function handlePropertyChange( event:PropertyChangeEvent = null):void{
			if( event != null ) this.dispatchEvent(event);
			else{
				this.dispatchEvent(new PropertyChangeEvent(PropertyChangeEvent.PROPERTY_CHANGE, false, false, PropertyChangeEventKind.UPDATE));
			}
		}
		
		private var _labelIndex:Number = 0;
		private var _labels:Array = new Array();
		public function resetLabels():void{
			this._labelIndex = 0;
			for each(var lab:Label in this._labels){
				lab.visible = false;
			}
		}
		public function getLabel():Label{
			var lab:Label;
			if(this._labels.length > this._labelIndex){
				lab = this._labels[this._labelIndex];
				lab.visible = true;
				this._labelIndex++;
			}
			else{
				lab = new Label();
				this.addChild(lab);
				this._labels.push(lab);
			}
			return lab;
		}
	}
}